package com.dongdongshop.front.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.hibernate.validator.constraints.Currency;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("login")
public class LoginController {

    private Logger logger= LoggerFactory.getLogger(LoginController.class);

    @RequestMapping("toLogin")
    public String toLogin(){
        return "admin/login";
    }

    @RequestMapping("toIndex")
    public String toIndex(){
        return "index";
    }

    //登录
    @RequestMapping("dengLu")
    public String dengLu(String username, String password, Model model){
        //1,获取subject
        Subject subject= SecurityUtils.getSubject();
        //2,将参数封装成token对象
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        //登录
        try {
            subject.login(token);
            /*String name = token.getUsername();
            Session session = subject.getSession();
            session.setAttribute( "name", name );*/
            return "redirect:/login/toIndex";//登录成功
        }catch (UnknownAccountException e){//账号(用户不存在)
            //logger.info("异常>>>>>",e);
            model.addAttribute("message","用户不存在");
            return "admin/login";
        }catch (IncorrectCredentialsException e){//密码不正确
            //logger.info("异常密码>>>>>",e);
            model.addAttribute("message","密码不正确");
            return "admin/login";
        }
    }
}
